/**
 * 2019年2月20日上午10:30:23
 * @author 谢进财
 */
package com.baihang.project.ds.service;

import java.util.List;
import java.util.Random;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.util.TypeUtils;
import com.baihang.framework.dao.Record;
import com.baihang.framework.kit.DateKit;
import com.baihang.framework.kit.JsonKit;
import com.baihang.framework.kit.StrKit;
import com.baihang.framework.kit.database.RedisKit;
import com.baihang.framework.service.BaseService;
import com.baihang.project.ds.model.FangYuanModel;

import redis.clients.jedis.Jedis;

/**
 * @author whati
 *
 */
@Service
public class RoomMonitorRedisService extends BaseService {
	private static Logger logger = LoggerFactory.getLogger(RoomMonitorRedisService.class);
	private Jedis jedis = RedisKit.getJedis();
	//单个翻红
	public void singleFanHong(int id) {
		//直接变蓝
		String modelJson = jedis.hmget("rooms", String.valueOf(id)).get(0);
		FangYuanModel  model = JSON.parseObject(modelJson, new TypeReference<FangYuanModel>() {});		
		model.setD_Monitor("2");
		TypeUtils.compatibleWithFieldName = true;
		jedis.hset("rooms", String.valueOf(id), JSON.toJSONString(model));
		
		String D_OperationRemark = model.getD_OperationRemark();
		//随机变红
		Random random = new Random();		
		long bianhong = random.nextInt(30);
		ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1,
                new BasicThreadFactory.Builder().namingPattern("socket-schedule-pool-%d").daemon(true).build());
          
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                    	 try {															
								TimeUnit.SECONDS.sleep(bianhong);
								System.err.println(bianhong+"线程操作");
								String operationRemark =String.format("%s|S管理:/%s",D_OperationRemark, DateKit.getCurrentDate(DateKit.Format_DateTime));
								String modelJson = jedis.hmget("rooms", String.valueOf(id)).get(0);
								FangYuanModel  model = JSON.parseObject(modelJson, new TypeReference<FangYuanModel>() {});		
								model.setD_Monitor("3");
								model.setD_OperationRemark(operationRemark);
								TypeUtils.compatibleWithFieldName = true;
								jedis.hset("rooms", String.valueOf(id), JSON.toJSONString(model));
								jedis.hdel("nkRooms", String.valueOf(id));//删除内控中记录，防止被一键翻红
                    	 } catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} 
                    }
                });
	}
	//一键翻红
	public String moreFanHong() {
		Random random = new Random();
		//查出所有被预定状态的房源
		List<String> list = jedis.hvals("nkRooms");
		
		if(list!=null && list.size()>0) {
			
			ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1,
					new BasicThreadFactory.Builder().namingPattern("socket-schedule-pool-%d").daemon(true).build());
			for(String rec:list) {				
				FangYuanModel  model = JSON.parseObject(rec, new TypeReference<FangYuanModel>() {});		
				logger.info(String.format("%d号房间在直接变蓝", model.getD_ID()));
				model.setD_Monitor("2");
				TypeUtils.compatibleWithFieldName = true;
				jedis.hset("rooms", String.valueOf(model.getD_ID()), JSON.toJSONString(model));				
				//随机变红
				long bianhong = random.nextInt(30);				
				executorService.schedule(new Runnable() {
					@Override
					public void run() {
						/*TimeUnit.SECONDS.sleep(bianlan);
						System.err.println(String.format("%d号房间在%d秒被翻蓝", rec.getInt("D_ID"),bianlan));*/
						FangYuanModel  model = JSON.parseObject(rec, new TypeReference<FangYuanModel>() {});		
						String D_OperationRemark = model.getD_OperationRemark();
						logger.info(String.format("%d号房间在%d秒被翻红", model.getD_ID(),bianhong));
						String operationRemark =String.format("%s|S管理:/%s",D_OperationRemark, DateKit.getCurrentDate(DateKit.Format_DateTime));
						model.setD_Monitor("3");
						model.setD_OperationRemark(operationRemark);
						TypeUtils.compatibleWithFieldName = true;
						jedis.hset("rooms", String.valueOf(model.getD_ID()), JSON.toJSONString(model));
					}
				},bianhong,TimeUnit.SECONDS);
			}
			executorService.shutdown();
			
			StringBuilder sb = new StringBuilder("[");
			for(int i=0;i<list.size();i++) {
				sb.append(list.get(i)+",");
			}
			sb.delete(sb.length()-1, sb.length());
			sb.append("]");
			return sb.toString();
		}else {
			return "0";
		}
	}
	//预定，取消预定，退定
	public boolean RoomGuideAjax(String action,String name,String tel,String cardno,int roomid) {
		//获取房源
		String modelJson = jedis.hmget("rooms", String.valueOf(roomid)).get(0);
		FangYuanModel  model = JSON.parseObject(modelJson, new TypeReference<FangYuanModel>() {});

		if("setroomorder".equals(action)) {//预定
			String operationRemark =String.format("H管理:/%s", DateKit.getCurrentDate(DateKit.Format_DateTime));
			if(StrKit.isEmpty(tel)) {//空绑定,房源只改变销控状态，不与认筹用户绑定
				model.setD_Monitor("1");
				model.setD_OperationRemark(operationRemark);
			}else {
				model.setD_Monitor("1");
				model.setD_Operation(tel);
				model.setD_OperationRemark(operationRemark);				
			}
			TypeUtils.compatibleWithFieldName = true;
			String obJson =JSON.toJSONString(model);
			jedis.hset("rooms", String.valueOf(roomid), obJson);
			jedis.hset("nkRooms", String.valueOf(roomid),obJson);//内控预定表
		}else if("roomunorder".equals(action)) {//取消预定
			model.setD_Monitor("0");
			model.setD_Operation("管理员");
			String operationRemark =String.format("%s;S管理:/%s", model.getD_OperationRemark(),DateKit.getCurrentDate(DateKit.Format_DateTime));
			model.setD_OperationRemark(operationRemark);
			TypeUtils.compatibleWithFieldName = true;
			String obJson =JSON.toJSONString(model);
			jedis.hset("rooms", String.valueOf(roomid), obJson);
			jedis.hdel("nkRooms", String.valueOf(roomid));
		}else if("setroomunred".equals(action)) {//退订
			model.setD_Monitor("0");
			model.setD_Operation("管理员");
			String operationRemark =String.format("%s;S管理:/%s", model.getD_OperationRemark(),DateKit.getCurrentDate(DateKit.Format_DateTime));
			model.setD_OperationRemark(operationRemark);
			TypeUtils.compatibleWithFieldName = true;
			String obJson =JSON.toJSONString(model);
			jedis.hset("rooms", String.valueOf(roomid), obJson);
		}
		return true;
	}
	//一键还原
	public boolean moreReset() {	
		List<String> list = jedis.hvals("nkRooms");		
		if(list!=null && list.size()>0) {
			for(String rec:list) {				
				FangYuanModel  model = JSON.parseObject(rec, new TypeReference<FangYuanModel>() {});		
				model.setD_Monitor("0");
				model.setD_Operation("管理员");
				String operationRemark =String.format("%s;Y管理:/%s", model.getD_OperationRemark(),DateKit.getCurrentDate(DateKit.Format_DateTime));
				model.setD_OperationRemark(operationRemark);
				TypeUtils.compatibleWithFieldName = true;
				jedis.hset("rooms", String.valueOf(model.getD_ID()), JSON.toJSONString(model));
				jedis.hdel("nkRooms", String.valueOf(model.getD_ID()));
			}
		}
		
		return true;

	}
	public String checkRoomState() {
		List<String> list = jedis.hvals("rooms");
		StringBuilder sb = new StringBuilder("[");
		for(int i=0;i<list.size();i++) {
			sb.append(list.get(i)+",");
		}
		sb.delete(sb.length()-1, sb.length());
		sb.append("]");
		return JsonKit.toDoubleJson2("true", sb.toString());
	}
	
	public static void main(String[] args) {
		Jedis jedis = RedisKit.getJedis();
		Random random = new Random();
		//查出所有被预定状态的房源
		List<String> list = jedis.hvals("nkRooms");
		
		if(list!=null && list.size()>0) {
			/*for(String rec:list) {
				//直接变蓝;
				logger.info(rec);
				logger.info("直接变蓝");
				FangYuanModel  model = JSON.parseObject(rec, new TypeReference<FangYuanModel>() {});		
				model.setD_Monitor("2");
				TypeUtils.compatibleWithFieldName = true;
				jedis.hset("rooms", String.valueOf(model.getD_ID()), JSON.toJSONString(model));				
			}*/
			
			ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1,
					new BasicThreadFactory.Builder().namingPattern("socket-schedule-pool-%d").daemon(true).build());
			for(String rec:list) {
				logger.info("直接变蓝");
				FangYuanModel  model = JSON.parseObject(rec, new TypeReference<FangYuanModel>() {});		
				model.setD_Monitor("2");
				TypeUtils.compatibleWithFieldName = true;
				jedis.hset("rooms", String.valueOf(model.getD_ID()), JSON.toJSONString(model));	
				//随机变红
				long bianhong = random.nextInt(30);				
				executorService.schedule(new Runnable() {
					@Override
					public void run() {
						System.err.println(rec);
						FangYuanModel  model = JSON.parseObject(rec, new TypeReference<FangYuanModel>() {});		
						String D_OperationRemark = model.getD_OperationRemark();
						System.err.println(String.format("%d号房间在%d秒被翻红", model.getD_ID(),bianhong));
						String operationRemark =String.format("%s|S管理:/%s",D_OperationRemark, DateKit.getCurrentDate(DateKit.Format_DateTime));
						model.setD_Monitor("3");
						model.setD_OperationRemark(operationRemark);
						TypeUtils.compatibleWithFieldName = true;
						jedis.hset("rooms", String.valueOf(model.getD_ID()), JSON.toJSONString(model));
					}
				},bianhong,TimeUnit.SECONDS);
			}
			executorService.shutdown();
		}
	}
}
